package com.hzz.web.app.report;

import com.hzz.api.area.IAreaService;
import com.hzz.api.report.IReportEventService;
import com.hzz.api.river.IRiverInfoService;
import com.hzz.api.user.IOrgInfoService;
import com.hzz.api.user.IUserService;
import com.hzz.dto.area.AreaDto;
import com.hzz.dto.report.ReportEventAddDto;
import com.hzz.dto.report.ReportEventDto;
import com.hzz.dto.report.ReportEventTreatmentDto;
import com.hzz.dto.river.RiverInfoDto;
import com.hzz.dto.user.OrgInfoDto;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.NoAuthorize;
import com.hzz.framework.annotation.RfUser2Bean;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.JwtUtil;
import com.hzz.framework.util.ValidatorUtil;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(description = "事件上报")
@RestController("ApiReportEventController")
@Slf4j
public class ReportEventController extends BaseController {
	@Autowired
	IReportEventService reportEventService;
	@Autowired
	IAreaService areaService;
	@Autowired
	IOrgInfoService orgInfoService;
	@Autowired
	IUserService userService;
	@Autowired
	IRiverInfoService riverInfoService;
	static final String acPrefix = "/api/report/reportEvent/";

	// @RequiresPermissions(value = {"reportEventPatrol:menu",
	// "reportEventComplaint:menu",}, logical = Logical.OR)
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = acPrefix + "page/{pageNum}")
	@ApiOperation(value = "信息分页(未删除)")
	public Response page(@RequestBody ReportEventDto dto, @PathVariable("pageNum") Integer pageNum) {
		log.info("page.........");
		Response result = new Response();
		try {
			dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
			dto.setPageNum(pageNum);
			dto.setDelFlag(0);
			if (dto.getReportingType() == null) {
				return Response.error("上报类型必传!");
			}
			UserDto userDto = JwtUtil.getSubject(UserDto.class);
			// 用户类型
			dto.setUserType(userDto.getType());
			dto.setCurrUserId(userDto.getId());
			// 用户河道
			if (userDto.getRiverId() != null) {
				String[] riverIdArr = userDto.getRiverId().split(",");
				if (riverIdArr != null && riverIdArr.length > 0) {
					List<Long> riverIds = new ArrayList<>();
					for (int i = 0; i < riverIdArr.length; i++) {
						String riverId = riverIdArr[i];
						if (ValidatorUtil.isEmpty(riverId)) {
							continue;
						}
						riverIds.add(Long.parseLong(riverId));
					}
					dto.setRiverIds(riverIds);
				}
			}
			result.data = PageUtil.copy(reportEventService.findDataIsPage(dto));
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	// @RequiresPermissions(value = {"reportEventPatrol:info",
	// "reportEventComplaint:info",}, logical = Logical.OR)
	@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
	@ApiOperation(value = "事件详情")
	public Response info(@PathVariable("id") Long id) {
		log.info("info.........");
		Response result = new Response();
		try {
			ReportEventDto dto = new ReportEventDto();
			dto.setId(id);
			dto.setDelFlag(0);
			UserDto userDto = JwtUtil.getSubject(UserDto.class);
			dto.setReportingUserId(userDto.getId());
			result.data = reportEventService.findDataById(dto);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	// @RequiresPermissions(value = {"reportEventPatrol:add",
	// "reportEventComplaint:add",}, logical = Logical.OR)
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = acPrefix + "newevent")
	@RfUser2Bean
	@ALogOperation(type = "事件上报", desc = "巡查事件")
	@ApiOperation(value = "事件上报")
	public Response newevent(@Validated @RequestBody ReportEventAddDto dto2, BindingResult bindingResult) {
		log.info("newevent.........");
		Response result = new Response(0, "success");
		try {
			if (bindingResult.hasErrors()) {
				String errorMsg = "";
				List<ObjectError> errorList = bindingResult.getAllErrors();
				for (ObjectError error : errorList) {
					errorMsg += (error.getDefaultMessage()) + ";";
				}
				result = Response.error(errorMsg);
			} else {
				ReportEventDto dto = copyTo(dto2, ReportEventDto.class);
				// 事件上报 所在河道 事件类型 事件描述 处理方式 照片（0/9）
				if (dto.getReportingType() == null) {
					return Response.error("上报类型必传!");
				}
				if (dto.getRiverId() == null) {
					return Response.error("上报河道必传!");
				}
				if (ValidatorUtil.isEmpty(dto.getTreatmentPrePics())) {
					return Response.error("处理前照片必填!");
				}
				UserDto userDto = JwtUtil.getSubject(UserDto.class);
				if (dto.getTreatmentType() == 0) {
					dto.setState(2);
					dto.setTreatmentDate(new Date());
					dto.setTreatmentAreaId(userDto.getAreaId());
					dto.setTreatmentAreaName(userDto.getAreaName());
					dto.setTreatmentOrgId(userDto.getOrgId());
					dto.setTreatmentOrgName(userDto.getOrgName());
					dto.setTreatmentUserId(userDto.getId());
					dto.setTreatmentUserName(userDto.getName());
					if (ValidatorUtil.isEmpty(dto.getTreatmentPostPics())) {
						return Response.error("处理后照片必填!");
					}
				} else {
					dto.setState(1);
				}
				if (dto.getTreatmentType() == 2) {
					setDataByHzbOrg(dto);
				}
				// 选择上报人员
				dto.setReportingUserId(userDto.getId());
				userDto = userService.findDataById(userDto);
				if (userDto != null) {
					dto.setReportingUserName(userDto.getName());
					dto.setReportingUserCellphone(userDto.getCellphone());
					// 选择处理人员
					if (dto.getTreatmentUserId() != null) {
						dto.setTreatmentUserName(userDto.getName());
					}
				}
				// 选择处理河段
				if (dto.getTreatmentReachId() != null) {
					RiverInfoDto riverInfoDto = new RiverInfoDto();
					riverInfoDto.setId(dto.getTreatmentReachId());
					riverInfoDto = riverInfoService.findDataById(riverInfoDto);
					if (riverInfoDto != null) {
						dto.setTreatmentReachName(riverInfoDto.getName());
					}
				}
				if (ValidatorUtil.notEmpty(dto.getRiverId())) {
					dto.setCurrentTreatmentRiverId(Long.parseLong(dto.getRiverId()));
					RiverInfoDto riverInfoDto = new RiverInfoDto();
					riverInfoDto.setId(dto.getCurrentTreatmentRiverId());
					riverInfoDto = riverInfoService.findDataById(riverInfoDto);
					if (riverInfoDto != null) {
						dto.setParentTreatmentRiverId(riverInfoDto.getParentId());
					}
				}
				dto.setCreateId(userDto.getId());
				result = reportEventService.newEvent(dto);
			}
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	OrgInfoDto getHzbOrgInfo() throws Exception {
		OrgInfoDto orgDto = new OrgInfoDto();
		orgDto.setId(CommonConstant.HZB_ORG_ID);
		OrgInfoDto orgInfoDto = orgInfoService.findDataById(orgDto);
		if (orgInfoDto == null) {
			throw new RuntimeException("河长办所属部门不存在,请联系管理员!");
		}
		return orgInfoDto;
	}

	void setDataByHzbOrg(ReportEventDto dto) throws Exception {
		OrgInfoDto orgInfoDto = getHzbOrgInfo();
		dto.setTreatmentOrgId(orgInfoDto.getId());
		dto.setTreatmentOrgName(orgInfoDto.getName());
	}

	void setDataByHzbOrg(ReportEventTreatmentDto dto) throws Exception {
		OrgInfoDto orgInfoDto = getHzbOrgInfo();
		dto.setTreatmentOrgId(orgInfoDto.getId());
		dto.setTreatmentOrgName(orgInfoDto.getName());
	}

	// @RequiresPermissions(value = {"reportEventPatrol:edit",
	// "reportEventComplaint:edit",}, logical = Logical.OR)
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = acPrefix + "treatment")
	@RfUser2Bean
	@ALogOperation(type = "事件处理", desc = "巡查事件")
	@ApiOperation(value = "事件处理")
	public Response treatment(@RequestBody ReportEventTreatmentDto dto) {
		log.info("treatment.........");
		Response result = new Response(0, "success");
		try {
			if (dto.getTreatmentType() == null) {
				return Response.error("处理方式不能为空");
			}
			if (dto.getId() == null) {
				return Response.error("事件ID不能为空");
			}
			ReportEventDto reportEventDto = reportEventService.findDataById(copyTo(dto, ReportEventDto.class));
			if (reportEventDto == null) {
				return Response.error("处理失败,事件不存在!");
			}
			// 用户级别 村级河长允许上报镇级河长处理；镇级河长允许再上报县级河长、允许分配处理；县级河长仅允许分配处理，不允许上报处理
			UserDto userDto = JwtUtil.getSubject(UserDto.class);
			boolean isCurrentTreatmentRiverId = false;
			// 事件处理方式
			switch (dto.getTreatmentType()) {
			case 0: { // 0直接处理
				dto.setTreatmentType(null);
				break;
			}
			case 1: { // 1分配处理
				// 河长办人员不允许分配、报河长处理，允许报上级河长
				if (CommonConstant.TYPES_各河长.indexOf(userDto.getType()) == -1) {
					return Response.error("处理失败,无分配权限!");
				}
				break;
			}
			case 2: { // 2报河长办处理
				setDataByHzbOrg(dto);
				break;
			}
			case 3: { // 3报上级河长处理
				// 当前河长级别
				if (userDto.getCurrAreaType() < 4) {
					return Response.error("处理失败,无法继续上报!");
				}
				isCurrentTreatmentRiverId = true;
				break;
			}
			}
			if (isCurrentTreatmentRiverId) {
				// 当前处理人所在河道id
				Long currentTreatmentRiverId = null;
				if (CommonConstant.TYPES_各河长.indexOf(userDto.getType()) != -1) {
					// 河长
					currentTreatmentRiverId = reportEventDto.getParentTreatmentRiverId();
				} else {
					// 普通用户
					currentTreatmentRiverId = Long.parseLong(userDto.getRiverId());
				}
				if (currentTreatmentRiverId != null) {
					dto.setCurrentTreatmentRiverId(currentTreatmentRiverId);
					RiverInfoDto riverInfoDto = new RiverInfoDto();
					riverInfoDto.setId(currentTreatmentRiverId);
					riverInfoDto = riverInfoService.findDataById(riverInfoDto);
					if (riverInfoDto != null) {
						dto.setParentTreatmentRiverId(riverInfoDto.getParentId());
					}
				}
			}
			// 1 事件处理(分配处理)
			// 处理人角色
			// 选择行政区划
			if (ValidatorUtil.notEmpty(dto.getTreatmentAreaId())) {
				AreaDto area = areaService.findDataById(Long.parseLong(dto.getTreatmentAreaId()));
				if (area != null) {
					dto.setTreatmentAreaName(area.getName());
				}
			}
			// 选择部门
			if (dto.getTreatmentOrgId() != null && dto.getTreatmentType() != 2) {
				OrgInfoDto orgInfoDto = new OrgInfoDto();
				orgInfoDto.setId(dto.getTreatmentOrgId());
				orgInfoDto = orgInfoService.findDataById(orgInfoDto);
				if (orgInfoDto != null) {
					dto.setTreatmentOrgName(orgInfoDto.getName());
				}
			}
			// 选择处理人员
			if (dto.getTreatmentUserId() != null && dto.getTreatmentType() == 1) {
				UserDto paramUserDto = new UserDto();
				paramUserDto.setId(dto.getTreatmentUserId());
				paramUserDto = userService.findDataById(paramUserDto);
				if (paramUserDto != null) {
					dto.setTreatmentUserName(paramUserDto.getName());
				}
			}
			if (ValidatorUtil.notEmpty(dto.getTreatmentPostPics())) {
				dto.setState(2);
				dto.setTreatmentDate(new Date());
				dto.setTreatmentAreaId(userDto.getAreaId());
				dto.setTreatmentAreaName(userDto.getAreaName());
				dto.setTreatmentOrgId(userDto.getOrgId());
				dto.setTreatmentOrgName(userDto.getOrgName());
				dto.setTreatmentUserId(userDto.getId());
				dto.setTreatmentUserName(userDto.getName());
			} else {
				dto.setState(1);
			}
			// 选择处理河段
			if (dto.getTreatmentReachId() != null) {
				RiverInfoDto riverInfoDto = new RiverInfoDto();
				riverInfoDto.setId(dto.getTreatmentReachId());
				riverInfoDto = riverInfoService.findDataById(riverInfoDto);
				if (riverInfoDto != null) {
					dto.setTreatmentReachName(riverInfoDto.getName());
				}
			}
			result = reportEventService.treatment(dto);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@NoAuthorize
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = acPrefix + "newEventForWechat")
	@RfUser2Bean
	@ALogOperation(type = "公众投诉", desc = "巡查事件")
	@ApiOperation(value = "公众投诉")
	public Response newEventForWechat(@Validated @RequestBody ReportEventDto dto2, BindingResult bindingResult) {
		log.info("newEventForWechat.........{}", dto2);
		Response result = new Response(0, "success");
		try {
			if (bindingResult.hasErrors()) {
				String errorMsg = "";
				List<ObjectError> errorList = bindingResult.getAllErrors();
				for (ObjectError error : errorList) {
					errorMsg += (error.getDefaultMessage()) + ";";
				}
				result = Response.error(errorMsg);
			} else {
				ReportEventDto dto = copyTo(dto2, ReportEventDto.class);
				// 事件上报 所在河道 事件类型 事件描述 处理方式 照片（0/9）
				if (dto.getReportingType() == null) {
					return Response.error("上报类型必传!");
				}
				if (ValidatorUtil.isEmpty(dto.getTreatmentPrePics())) {
					return Response.error("处理前照片必填!");
				}
				dto.setState(1);
				dto.setReportingDate(new Date());
				if (ValidatorUtil.notEmpty(dto.getRiverId())) {
					dto.setCurrentTreatmentRiverId(Long.parseLong(dto.getRiverId()));
					RiverInfoDto riverInfoDto = new RiverInfoDto();
					riverInfoDto.setId(dto.getCurrentTreatmentRiverId());
					riverInfoDto = riverInfoService.findDataById(riverInfoDto);
					if (riverInfoDto != null) {
						dto.setParentTreatmentRiverId(riverInfoDto.getParentId());
					}
				}
				result = reportEventService.newEvent(dto);
			}
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}
}
